package com.cheng.operation.impl;

import com.cheng.common.exception.CommonException;
import com.cheng.common.utils.CodeUtil;
import com.cheng.common.utils.IdUtil;
import com.cheng.common.utils.PswdUtil;
import com.cheng.common.utils.StringUtil;
import com.cheng.data.entity.UserInfoEntity;
import com.cheng.data.entity.UserRoleEntity;
import com.cheng.data.vo.ReqPageInfoVO;
import com.cheng.data.vo.RespPageInfoVO;
import com.cheng.data.vo.SettingInfoVO;
import com.cheng.data.vo.UserInfoVO;
import com.cheng.operation.GvmtTypeInfOperation;
import com.cheng.operation.UserOperation;
import com.cheng.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author: ChengJW
 * @date: 2021/11/14 10:19
 * @version: 1.0
 * @description: 用户信息业务逻辑处理
 */
@Service
public class UserOperationImpl implements UserOperation {

    private final static Logger log = LoggerFactory.getLogger(UserOperationImpl.class);

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private GvmtTypeInfOperation gvmtTypeInfOperation;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private ComUploadService comUploadService;

    @Autowired
    private SettingInfoService settingInfoService;

    /**
     * @author: ChengJW
     * @params: [pageInfoVO]
     * @return: com.cheng.data.vo.RespPageInfoVO
     * @date: 2021/11/14
     * @description: 查询用户列表信息，并分页按照统一格式返回
     */
    @Override
    public RespPageInfoVO queryUserList(ReqPageInfoVO pageVO) throws CommonException {

        if (null == pageVO){
            log.error("用户信息查询条件 ReqPageInfoVO 为空，无法进行下一步操作");
            return null;
        }
        UserInfoEntity entity = new UserInfoEntity();
        //第一个查询条件存入用户名称(账号)
        entity.setUrNm(String.valueOf(pageVO.getQryReqFir()));
        //第二个查询条件存入用户姓名
        entity.setUrRealNm("%"+String.valueOf(pageVO.getQryReqSeco())+"%");
        entity.setUrDwCode(pageVO.getUserCode());
        PageInfo<UserInfoVO> pageInfo = PageHelper.startPage(pageVO.getPageNum(),pageVO.getPageSize()).doSelectPageInfo(() -> userInfoService.queryUserList(entity));
        List<UserInfoVO> userInfoVOList = pageInfo.getList();
        if (null != userInfoVOList && userInfoVOList.size() > 0){
            for (UserInfoVO vo : userInfoVOList){
                vo.setUrDwCode(gvmtTypeInfOperation.queryGvmtTypeInfNmByCode(vo.getUrDwCode()));
                vo.setUrBmCode(departmentService.queryDepartmentNmByCode(vo.getUrBmCode()));
            }
        }
        RespPageInfoVO respPageInfoVO = new RespPageInfoVO();
        respPageInfoVO.setList(userInfoVOList);
        respPageInfoVO.setPageNum(pageInfo.getPageNum());
        respPageInfoVO.setPageSize(pageInfo.getPageSize());
        respPageInfoVO.setPageCount(pageInfo.getTotal());
        return respPageInfoVO;
    }

    /**
     * @author: ChengJW
     * @params: [entity]
     * @return: int
     * @date: 2021/11/14
     * @description: 新增用户信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertUserInfo(UserInfoVO userInfoVO) throws CommonException {
        if (null != userInfoVO){
            //账号密码不能为空
           if (StringUtil.isNull(userInfoVO.getUrNm())|| StringUtil.isNull(userInfoVO.getUrPwd())){
               log.error("账户或密码为空");
               throw new CommonException("CJW202111010035","UserOperationImpl","insertUserInfo");
           }
           List<UserInfoEntity> list = userInfoService.queryUserListByNm(userInfoVO.getUrNm());
           //账号不能重复添加
           if (null != list && list.size() > 0){
               log.error("账号已经存在，不能继续添加");
               throw new CommonException("CJW202111010036","UserOperationImpl","insertUserInfo");
           }
        }
        UserInfoEntity entity = new UserInfoEntity();
        BeanUtils.copyProperties(userInfoVO,entity);
        //用户ID
        String urId = IdUtil.getUserId();
        entity.setUrId(urId);
        entity.setUrDelTp("0");
        //密码进行加密
        entity.setUrPwd(PswdUtil.createPswd(CodeUtil.SALT,entity.getUrPwd()));
        entity.setStDt(new Date());
        entity.setUtDt(new Date());
        entity.setUrPhotoPath(CodeUtil.DEFAULT_PROFILE_PHOTO_PATH);
        userInfoService.insertUserInfo(entity);
        //插入用户-角色表
        UserRoleEntity userRoleEntity = new UserRoleEntity();
        userRoleEntity.setUlId(IdUtil.getULId(0));
        userRoleEntity.setUrId(urId);
        userRoleEntity.setRoId(userInfoVO.getRoleInfoVO().getRoId());
        userRoleEntity.setStDt(new Date());
        userRoleEntity.setUtDt(new Date());
        userRoleService.insertUserRoleInfo(userRoleEntity);
    }

    /**
     * @author: ChengJW
     * @params: [userInfoVO]
     * @return: void
     * @date: 2021/11/14
     * @description: 修改用户信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserInfo(UserInfoVO userInfoVO) throws CommonException {

        if (null == userInfoVO){
            log.error("用户信息为空");
            throw new CommonException("CJW202111010037","UserOperationImpl","updateUserInfo");
        }
        if (StringUtil.isNull(userInfoVO.getUrPwd())){
            log.error("用户密码不能为空");
            throw new CommonException("CJW202111010038","UserOperationImpl","updateUserInfo");
        }
        //通过 urId 查询用户信息，再替换修改的信息
        UserInfoEntity entity = userInfoService.queryUserInfo(userInfoVO.getUrId());
        if (null == entity){
            log.error("根据ID查询不到用户信息");
            throw new CommonException("CJW202111010039","UserOperationImpl","updateUserInfo");
        }
        entity.setUrNm(userInfoVO.getUrNm());
        entity.setUrPwd(PswdUtil.createPswd(userInfoVO.getUrPwd()));
        entity.setUrRealNm(userInfoVO.getUrRealNm());
        entity.setUrAge(userInfoVO.getUrAge());
        entity.setUrSex(userInfoVO.getUrSex());
        entity.setUrAds(userInfoVO.getUrAds());
        entity.setUrTel(userInfoVO.getUrTel());
        entity.setUrDwCode(userInfoVO.getUrDwCode());
        entity.setUrBmCode(userInfoVO.getUrBmCode());
        entity.setUrResv(userInfoVO.getUrResv());
        entity.setUtDt(new Date());
        userInfoService.updateUserInfo(entity);

        //修改 user_role 表信息
        UserRoleEntity userRoleEntity = new UserRoleEntity();
        userRoleEntity.setUrId(userInfoVO.getUrId());
        List<UserRoleEntity> list = userRoleService.queryUserRoleInfo(userRoleEntity);
        if (null == list || list.size() == 0){
            log.error("用户角色中间表查询失败");
            throw new CommonException("CJW202111010040","UserOperationImpl","updateUserInfo");
        }
        UserRoleEntity urEntity = list.get(0);
        urEntity.setRoId(userInfoVO.getRoleInfoVO().getRoId());
        userRoleService.updateUserRoleInfo(urEntity);
    }

    /**
    * @author: ChengJW
    * @params: [userInfoVO]
    * @return: void
    * @date: 2021/11/14
    * @description: 删除用户信息
    */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteUserInfo(UserInfoVO userInfoVO) throws CommonException {
        if(null == userInfoVO || StringUtil.isNull(userInfoVO.getUrId())){
            log.error("用户信息为空");
            throw new CommonException("CJW202111010037","UserOperationImpl","deleteUserInfo");
        }
        UserInfoEntity entity = new UserInfoEntity();
        BeanUtils.copyProperties(userInfoVO,entity);
        //删除 user_info 表信息
        userInfoService.deleteUserInfo(entity);
        //删除 user_role 表信息
        UserRoleEntity userRoleEntity = new UserRoleEntity();
        userRoleEntity.setUrId(userInfoVO.getUrId());
        userRoleService.deleteUserRoleInfo(userRoleEntity);
    }

    /**
     * @author: ChengJW
     * @params: [urNm, oldUrPsd, newUrPsd]
     * @return: void
     * @date: 2021/11/20
     * @description: 修改用户密信息、头像
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUserInfo(UserInfoVO vo,String txTpCd) throws CommonException {
        if (null == vo || null == vo.getUrNm()){
            log.error("用户信息为空，无法进行下一步操作");
            throw new CommonException("CJW202111010037","UserOperationImpl","updateUserPswd");
        }
        //通过名称查询用户信息
        List<UserInfoEntity> list = userInfoService.queryUserListByNm(vo.getUrNm());
        if (null == list || list.size() == 0){
            log.error("根据用户名称，没有查询到用户信息");
            throw new CommonException("CJW202111010048","UserOperationImpl","updateUserPswd");
        }
        UserInfoEntity entity = list.get(0);
        //修改用户密码
        if ("02".equals(txTpCd)){
            if (StringUtil.isNull(vo.getUrPwd()) || StringUtil.isNull(vo.getUrNewPwd())){
                log.error("用户旧密码或新密码输入为空");
                throw new CommonException("CJW202111010049","UserOperationImpl","updateUserPswd");
            }
            //判断旧密码是否正确
            String password = entity.getUrPwd();
            if (!password.equals(PswdUtil.createPswd(CodeUtil.SALT,vo.getUrPwd()))){
                log.error("旧密码输入不正确");
                throw new CommonException("CJW202111010050","UserOperationImpl","updateUserPswd");
            }
            entity.setUrPwd(PswdUtil.createPswd(CodeUtil.SALT,vo.getUrNewPwd()));
        }else if ("01".equals(txTpCd)){
            //修改头像
            if (StringUtil.isNull(vo.getUrPhotoPath())){
                log.error("用户头像路径为空，无法进行下一步操作");
                throw new CommonException("CJW202111010051","UserOperationImpl","updateUserPswd");
            }
            //先删除原来的头像图片
            String photoPath = entity.getUrPhotoPath();
            String [] photoPathList = StringUtil.split(photoPath,"/");
            String Realpath = photoPathList[photoPathList.length-1];
            //判断是否是开发模式
            SettingInfoVO settingInfoVO = settingInfoService.getSettingVO(CodeUtil.IS_OPEN_DEVELOPMENT_CD);
            if (settingInfoVO == null || CodeUtil.DEVELOPMENT_MODEAL.equals(settingInfoVO.getSiRsrv2())){
                Realpath = CodeUtil.IMAGES_PATH + Realpath;
            }else {
                Realpath = settingInfoService.getSettingVO(CodeUtil.PROFILE_PHOTO_PATH).getSiRsrv2() + CodeUtil.SEPARATOR + Realpath;
            }
            File file = new File(Realpath);
            if (file.exists()){
                file.delete();
            }
            entity.setUrPhotoPath(vo.getUrPhotoPath());
        }else {
            //修改用户信息
            entity.setUrAds(vo.getUrAds());
            entity.setUrSex(vo.getUrSex());
            entity.setUrTel(vo.getUrTel());
            entity.setUrResv(vo.getUrResv());
            entity.setUrBmCode(vo.getUrBmCode());
            entity.setUrRealNm(vo.getUrRealNm());
            entity.setUrAge(vo.getUrAge());
        }
        entity.setUtDt(new Date());
        userInfoService.updateUserInfo(entity);
    }

    /**
    * @author: ChengJW
    * @params: [file]
    * @return: void
    * @date: 2021/11/22
    * @description: 文件上传，并回传文件存储名称
    */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String uploadPhoto(MultipartFile file) throws CommonException {
        return comUploadService.uploadFile(file);
    }

    /**
    * @author: ChengJW
    * @params: [userInfoVO]
    * @return: com.cheng.data.vo.UserInfoVO
    * @date: 2021/11/24
    * @description: 查询用户信息
    */
    @Override
    public UserInfoVO queryUserInfo(UserInfoVO userInfoVO) throws CommonException {

        List<UserInfoEntity> list = userInfoService.queryUserListByNm(userInfoVO.getUrNm());
        if (null != list && list.size() > 0){
            UserInfoEntity entity = list.get(0);
            UserInfoVO vo = new UserInfoVO();
            BeanUtils.copyProperties(entity,vo);
            return vo;
        }
        return null;
    }
}
